package com.yinhe.module.gs.verify;

import com.yinhe.common.annotation.Log;
import com.yinhe.common.config.YinHeConfig;
import com.yinhe.common.core.controller.BaseController;
import com.yinhe.common.core.domain.AjaxResult;
import com.yinhe.common.core.domain.entity.SysUser;
import com.yinhe.common.core.domain.model.LoginUser;
import com.yinhe.common.core.page.TableDataInfo;
import com.yinhe.common.enums.BusinessType;
import com.yinhe.common.utils.poi.ExcelUtil;
import com.yinhe.system.domain.YhFileVerify;
import com.yinhe.system.service.IYhFileVerifyService;
import com.yinhe.web.controller.tool.MD5Utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

import static com.yinhe.common.utils.SecurityUtils.getLoginUser;
import static java.awt.SystemColor.text;

/**
 * 文件审核Controller
 * 
 * @author gaoshuai
 * @date 2022-08-09
 */
@RestController
@RequestMapping("/gs/verify")
public class YhVerifyController extends BaseController
{
    @Autowired
    private IYhFileVerifyService yhFileVerifyService;

    /**
     * 查询文件审核列表
     */
    @PreAuthorize("@ss.hasPermi('gs:verify:list')")
    @GetMapping("/list")
    public TableDataInfo list(YhFileVerify yhFileVerify)
    {
        startPage();
        List<YhFileVerify> list = yhFileVerifyService.selectYhFileVerifyList(yhFileVerify);
        return getDataTable(list);
    }

    /**
     * 导出文件审核列表
     */
    @PreAuthorize("@ss.hasPermi('gs:verify:export')")
    @Log(title = "文件审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhFileVerify yhFileVerify)
    {
        List<YhFileVerify> list = yhFileVerifyService.selectYhFileVerifyList(yhFileVerify);
        ExcelUtil<YhFileVerify> util = new ExcelUtil<YhFileVerify>(YhFileVerify.class);
        util.exportExcel(response, list, "文件审核数据");
    }

    /**
     * 获取文件审核详细信息
     */
    @PreAuthorize("@ss.hasPermi('gs:verify:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(yhFileVerifyService.selectYhFileVerifyById(id));
    }

    /**
     * 新增文件审核
     */
    //@PreAuthorize("@ss.hasPermi('gs:verify:add')")
    @Log(title = "文件审核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhFileVerify yhFileVerify)
    {
        return toAjax(yhFileVerifyService.insertYhFileVerify(yhFileVerify));
    }


/*
* PDF接口
* */
@PostMapping("/filepost")
    public void filePost(@RequestBody YhFileVerify yhFileVerify) throws UnsupportedEncodingException, FileNotFoundException {

    //note1是pdf地址，note2是图片地址
    Long loginUserId = getUserId();
    String filePath = YinHeConfig.getUploadPath();

    String filePathq = YinHeConfig.getProfile();

    String path=filePathq+yhFileVerify.getNote1().substring(8);
    String name1=yhFileVerify.getNote1().substring(16);
    //系统生成的名字后面带日期，这里进行去除
    String[] firstname=name1.split("_");
    // System.out.println(firstname[0]+"firstname[0]");
    // System.out.println(name+"name");
    String str1 = name1.substring(name1.lastIndexOf(".")+1);
    //String str2 = name1.substring(str1.length()+1, name1.length());
    System.out.println(str1+"str1");
    //处理后的名字
    String name=firstname[0]+"."+str1;
    // System.out.println(str2+"str2");


    if(yhFileVerify.getNote1()!=null){




        HttpPost httpPost = new HttpPost("http://10.2.0.166:9091/api/filetransfer/uploadfile");
//      随机设计
        String boundary ="--------------4585696313564699";
        //设置请求头(百度好多都没有设置这个请求头)
        httpPost.setHeader("Content-Type","multipart/form-data;boundary="+boundary);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        //模拟浏览器
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //字符编码
        ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));

       // builder.addTextBody("name", "text",contentType);

        //builder.setCharset(Charset.forName("UTF-8"));
        builder.setBoundary(boundary);
        System.out.println(name+"name");
        //设置请求携带的参数
        builder.addTextBody("filePath", "/");
        builder.addTextBody("filename", name,contentType);
        builder.addTextBody("chunkNumber", "1");
        builder.addTextBody("chunkSize",  "3000");
        builder.addTextBody("relativePath", name,contentType);
        builder.addTextBody("totalChunks", "1");
        builder.addTextBody("totalSize", "3000");
        builder.addTextBody("currentChunkSize", "3000");
        builder.addTextBody("identifier", MD5Utils.generateMD5(name));
        builder.addTextBody("isPublic", "0");

        builder.addTextBody("userId", String.valueOf(loginUserId));
        File pdfFile = new File(path);
        builder.addPart("file",new FileBody(pdfFile));


//        file 文件这样写
//        builder.addPart("参数名",new FileBody(file));
        HttpEntity multipart = builder.build();
        HttpResponse resp = null;
        try {
            httpPost.setEntity(multipart);
            // 提交
            resp = client.execute(httpPost);
            //根据业务需求 自行调整
            HttpEntity entity = resp.getEntity();
            respContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
        }

    }

    // 获取当前登录用户
    LoginUser loginUser = getLoginUser();
    SysUser sysUser = loginUser.getUser();
    yhFileVerify.setDeptId(String.valueOf(sysUser.getDeptId()));
    yhFileVerify.setUserId(String.valueOf(sysUser.getUserId()));

    yhFileVerify.setFilename(name);

    yhFileVerify.setIdentifier(MD5Utils.generateMD5(name));
    yhFileVerify.setUsername(loginUser.getUser().getNickName());
    yhFileVerify.setNote1(path);
    yhFileVerify.setNote4(String.valueOf(0));
    if(name1.contains("pdf")){
        yhFileVerify.setNote2(name1);
    }else{
        yhFileVerify.setNote3(name1);
    }

    Integer i = yhFileVerifyService.insertYhFileVerify(yhFileVerify);
    System.out.println(i);



    }
    /*
     * 审核接口
     * */
    @PostMapping("/picfilepost")
    public void picfilePost(@RequestBody YhFileVerify yhFileVerify) throws UnsupportedEncodingException, FileNotFoundException {


        //note1是pdf地址，note2是图片地址
        Long loginUserId = getUserId();
        String filePath = YinHeConfig.getUploadPath();

        String filePathq = YinHeConfig.getProfile();

        String path=filePathq+yhFileVerify.getNote2().substring(8);
        String name1=yhFileVerify.getNote2().substring(16);
       //系统生成的名字后面带日期，这里进行去除
        String[] firstname=name1.split("_");
       // System.out.println(firstname[0]+"firstname[0]");
       // System.out.println(name+"name");
        String str1 = name1.substring(name1.lastIndexOf(".")+1);
      //  String str2 = name1.substring(str1.length()+1, name1.length());
        //处理后的名字
        String name=firstname[0]+"."+str1;
       // System.out.println(str2+"str2");



        if(yhFileVerify.getNote2()!=null){




            HttpPost httpPost = new HttpPost("http://10.2.0.166:9091/api/filetransfer/uploadfile");
//      随机设计
            String boundary ="--------------4585696313564699";
            //设置请求头(百度好多都没有设置这个请求头)
            httpPost.setHeader("Content-Type","multipart/form-data;boundary="+boundary);
            CloseableHttpClient client = HttpClients.createDefault();
            String respContent = null;
            //模拟浏览器
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //字符编码
            //字符编码
            ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));
           // builder.setCharset(Charset.forName("UTF-8"));
            builder.setBoundary(boundary);
            //设置请求携带的参数
            builder.addTextBody("filePath", "/");


            builder.addTextBody("filename", name,contentType);
            builder.addTextBody("chunkNumber", "1");
            builder.addTextBody("chunkSize",  "3000");
            builder.addTextBody("relativePath", name,contentType);
            builder.addTextBody("totalChunks", "1");
            builder.addTextBody("totalSize", "3000");
            builder.addTextBody("currentChunkSize", "3000");
            builder.addTextBody("identifier", MD5Utils.generateMD5(name));
            builder.addTextBody("isPublic", "0");

            builder.addTextBody("userId", String.valueOf(loginUserId));
            File pdfFile = new File(path);
            builder.addPart("file",new FileBody(pdfFile));


//        file 文件这样写
//        builder.addPart("参数名",new FileBody(file));
            HttpEntity multipart = builder.build();
            HttpResponse resp = null;
            try {
                httpPost.setEntity(multipart);
                // 提交
                resp = client.execute(httpPost);
                //根据业务需求 自行调整
                HttpEntity entity = resp.getEntity();
                respContent = EntityUtils.toString(entity, "UTF-8");
            } catch (Exception e) {
            }

        }



        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getUser();
        yhFileVerify.setDeptId(String.valueOf(sysUser.getDeptId()));
        yhFileVerify.setUserId(String.valueOf(sysUser.getUserId()));

        yhFileVerify.setFilename(name);

        yhFileVerify.setIdentifier(MD5Utils.generateMD5(name));
        yhFileVerify.setUsername(loginUser.getUser().getNickName());
        yhFileVerify.setNote1(path);
        yhFileVerify.setNote4(String.valueOf(0));
        if(name1.contains("pdf")){
            yhFileVerify.setNote2(name1);
        }else{
            yhFileVerify.setNote3(name1);
        }

        Integer i = yhFileVerifyService.insertYhFileVerify(yhFileVerify);
        System.out.println(i);



    }
    /*
     * 接口
     * */
    @PutMapping("/post")
    public AjaxResult doPost(@RequestBody YhFileVerify yhFileVerify) throws UnsupportedEncodingException, FileNotFoundException {


        HttpPost httpPost = new HttpPost("http://10.2.0.166:9091/api/filetransfer/uploadfile");
//      随机设计
        String boundary ="--------------4585696313564699";
        //设置请求头(百度好多都没有设置这个请求头)
        httpPost.setHeader("Content-Type","multipart/form-data;boundary="+boundary);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        //模拟浏览器
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //字符编码
        //builder.setCharset(Charset.forName("UTF-8"));
        builder.setBoundary(boundary);
        //设置请求携带的参数
        builder.addTextBody("filePath", yhFileVerify.getFilepath());


        builder.addTextBody("filename", yhFileVerify.getFilename());
        builder.addTextBody("chunkNumber", yhFileVerify.getChunkNumber());
        builder.addTextBody("chunkSize",  Long.toString(yhFileVerify.getChunkSize()));
        builder.addTextBody("relativePath", yhFileVerify.getRelativePath());
        builder.addTextBody("totalChunks", Long.toString(yhFileVerify.getTotalChunks()));
        builder.addTextBody("totalSize", Long.toString(yhFileVerify.getTotalSize()));
        builder.addTextBody("currentChunkSize", Long.toString(yhFileVerify.getCurrentChunkSize()));
        builder.addTextBody("identifier", yhFileVerify.getIdentifier());
        builder.addTextBody("isPublic", "1");
        builder.addTextBody("userId", "1");
        File pdfFile = new File(yhFileVerify.getNote1());
        builder.addPart("file",new FileBody(pdfFile));


//        file 文件这样写
//        builder.addPart("参数名",new FileBody(file));
        HttpEntity multipart = builder.build();
        HttpResponse resp = null;
        try {
            httpPost.setEntity(multipart);
            // 提交
            resp = client.execute(httpPost);
            //根据业务需求 自行调整
            HttpEntity entity = resp.getEntity();
            respContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
        }
        return toAjax(yhFileVerifyService.updateYhFileVerify(yhFileVerify));
    }
    /*
     * 是否共享接口
     * */
    @PutMapping("/sharepost")
    public AjaxResult sharePost(@RequestBody YhFileVerify yhFileVerify) throws UnsupportedEncodingException, FileNotFoundException {
        System.out.println("88888888888");
        HttpPost httpPost = new HttpPost("http://10.2.0.166:9091/api/file/shareupdate");
//      随机设计
        String boundary ="--------------4585696313564699";
        //设置请求头(百度好多都没有设置这个请求头)
        httpPost.setHeader("Content-Type","multipart/form-data;boundary="+boundary);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        //模拟浏览器
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //字符编码
        //字符编码
        ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));
        //builder.setCharset(Charset.forName("UTF-8"));
        builder.setBoundary(boundary);
        //设置请求携带的参数
        //去除.jpg等后缀
        String filename1= yhFileVerify.getFilename();
        String filenametrue=filename1.substring(0,filename1.lastIndexOf("."));
        builder.addTextBody("fileName", filenametrue,contentType);

        HttpEntity multipart = builder.build();
        HttpResponse resp = null;
        try {
            httpPost.setEntity(multipart);
            // 提交
            resp = client.execute(httpPost);
            //根据业务需求 自行调整
            HttpEntity entity = resp.getEntity();
            respContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
        }


        return toAjax(yhFileVerifyService.updateYhFileVerify(yhFileVerify));

    }
    /**
     * 修改文件审核
     */
    @PreAuthorize("@ss.hasPermi('gs:verify:edit')")
    @Log(title = "文件审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YhFileVerify yhFileVerify)
    {
        return toAjax(yhFileVerifyService.updateYhFileVerify(yhFileVerify));
    }

    /**
     * 删除文件审核
     */
    @PreAuthorize("@ss.hasPermi('gs:verify:remove')")
    @Log(title = "文件审核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yhFileVerifyService.deleteYhFileVerifyByIds(ids));
    }
}
